package com.sdry.service.impl.llm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.sdry.mapper.llm.CancellingStockMapper;
import com.sdry.model.jyy.Receive;
import com.sdry.model.llm.BarCode;
import com.sdry.model.llm.LlmCancellingStocks;
import com.sdry.model.lz.CodeMark;
import com.sdry.model.lz.Customer;
import com.sdry.model.lz.Materiel;
import com.sdry.model.lz.Warehouse;
import com.sdry.model.zc.ZcMaterielInfoEntity;
import com.sdry.service.llm.CancellingStockService;
import com.sdry.utils.PushExample;
import com.sdry.utils.StringUtil;

/**
 * 退库单service实现类
 * @Title:CanacellingStockServiceImp
 * @Package com.sdry.service.impl.llm
 * @author llm
 * @date 2019年5月14日
 * @version 2.0
 */
@Service
public class CanacellingStockServiceImp implements CancellingStockService{

	@Resource
	private CancellingStockMapper cancellingStockMapper;
	
	/**       
	 * 根据条件获取退库单总行数
	 * @param cancellingStock
	 * @return    
	 */
	@Override
	public int getCountConcellingStock(Map<String, Object> map) {
		return cancellingStockMapper.getCountConcellingStock(map);
	}

	/**      
	 * 根据条件分页查询退库单 
	 * @param map
	 * @return    
	 */
	@Override
	public List<LlmCancellingStocks> listPageConcellingStock(Map<String, Object> map) {
		List<LlmCancellingStocks> list = cancellingStockMapper.listPageConcellingStock(map);
		if(list.size() > 0){
			for(LlmCancellingStocks cs : list){
				if(cs.getWarehouseId() != null && !"".equals(cs.getWarehouseId())){
					Warehouse warehouse = cancellingStockMapper.getWarehouseById(cs.getWarehouseId());
					if(warehouse != null){
						cs.setWarehouse_address(warehouse.getWarehouse_address());
						cs.setUserName(warehouse.getUserName());
						cs.setPhone(warehouse.getPhone());
						cs.setWarehouse_name(warehouse.getWarehouse_name());
					}
				}
				if(cs.getClientId() != null && !"".equals(cs.getClientId())){
					Customer customer = cancellingStockMapper.getClientById(cs.getClientId());
					if(customer != null){
						cs.setContacts_name(customer.getContacts_name());
						cs.setContacts_tel(customer.getContacts_tel());
						cs.setCustomer_adress(customer.getCustomer_adress());
						cs.setCustomer_name(customer.getCustomer_name());
					}
				}
				if(cs.getStatus() == 1){
					cs.setCancellingStatus("已退库");
				}else{
					cs.setCancellingStatus("未退库");
				}
			}
		}
		return list;
	}

	/**       
	 * 新增退库单
	 * @param cancellingStock
	 * @return    
	 */
	@Override
	public Integer saveConcellingStock(LlmCancellingStocks cancellingStock) {
		return cancellingStockMapper.saveConcellingStock(cancellingStock);
	}

	/**   
	 * 修改退库单    
	 * @param cancellingStock
	 * @return    
	 */
	@Override
	public Integer updateConcellingStock(LlmCancellingStocks cancellingStock) {
		return cancellingStockMapper.updateConcellingStock(cancellingStock);
	}

	/**  
	 * 修改退库单2     
	 * @param map
	 * @return    
	 */
	@Override
	public Integer updateConcellingStock2(Map<String, Object> map) {
		return cancellingStockMapper.updateConcellingStock2(map);
	}
	
	/**    
	 * 批量删除退库单   
	 * @param ids
	 * @return    
	 */
	@Transactional(rollbackFor={Exception.class})
	public Integer deleteConcellingStock(String ids) {
		int isSuccess = 0;
		String[] split = ids.split(",");
		try {
			for (String id : split) {
				isSuccess = cancellingStockMapper.deleteConcellingStock(Long.parseLong(id));
			}
		}catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}
		return isSuccess;
	}

	/**   
	 * 发送退库单    
	 * @param roder
	 * @return    
	 */
	@Override
	public Integer sendConcellingStock(String roder) {
		int isSuccess = 1;
		//发送消息
		PushExample.testSendPush("您有一个新的退库单，单号是："+roder, "退库通知", "1", "2");
		return isSuccess;
	}

	/**     
	 * 获取所有供应商  
	 * @return    
	 */
	@Override
	public List<Customer> getAllCustomer() {
		return cancellingStockMapper.getAllCustomer();
	}

	/** 
	 * 获取所有仓库      
	 * @return    
	 */
	@Override
	public List<Warehouse> getAllWarehouse() {
		return cancellingStockMapper.getAllWarehouse();
	}

	/**    
	 * 获取所有退库单   
	 * @return    
	 */
	@Override
	public List<LlmCancellingStocks> getAllCancellingStock() {
		return cancellingStockMapper.getAllCancellingStock();
	}

	/**  
	 * 根据物料ID查询物料表     
	 * @param id
	 * @return    
	 */
	@Override
	public Materiel getMaterielByMid(Long id) {
		return cancellingStockMapper.getMaterielByMid(id);
	}

	/**   
	 * 根据客户ID获取供应商联系人信息    
	 * @param id
	 * @return    
	 */
	@Override
	public Customer getClientById(Long id) {
		return cancellingStockMapper.getClientById(id);
	}

	/**     
	 * 根据仓库ID获取管理员信息  
	 * @param id
	 * @return    
	 */
	@Override
	public Warehouse getWarehouseById(Long id) {
		return cancellingStockMapper.getWarehouseById(id);
	}

	/**      
	 * 获取所有不良品库
	 * @return    
	 */
	@Override
	public List<Warehouse> getAllBadnessWarehouse() {
		return cancellingStockMapper.getAllBadnessWarehouse();
	}

	/**       
	 * 根据仓库ID获取物料信息
	 * @param id
	 * @return    
	 */
	@Override
	public List<Materiel> getMaterielByWarehouseId(Long id) {
		return cancellingStockMapper.getMaterielByWarehouseId(id);
	}

	/**     
	 * 根据退库单编号查询退库单  
	 * @param cancellingNumber
	 * @return    
	 */
	@Override
	public LlmCancellingStocks getCancellingStockByNumber(String cancellingNumber) {
		return cancellingStockMapper.getCancellingStockByNumber(cancellingNumber);
	}

	/**      
	 * 根据仓库ID获取供应商信息 
	 * @param id
	 * @return    
	 */
	@Override
	public List<Customer> getCustomerByWarehouseId(Long id) {
		return cancellingStockMapper.getCustomerByWarehouseId(id);
	}

	/**   
	 * 根据供应商和SAP查询所有物料      
	 * @param map
	 * @return    
	 */
	@Override
	public List<Materiel> appGetMaterielByCustomerAndSAP(Map<String, Object> map) {
		return cancellingStockMapper.appGetMaterielByCustomerAndSAP(map);
	}

	/**       
	 * @param receiveNumber
	 * @return    
	 */
	@Override
	public Receive getReceiveByNumber(String receiveNumber) {
		return cancellingStockMapper.getReceiveByNumber(receiveNumber);
	}

	/**       
	 * @param number
	 * @return    
	 */
	@Override
	public List<CodeMark> getCodeByMaterielNum(String number) {
		return cancellingStockMapper.getCodeByMaterielNum(number);
	}

	/**       
	 * @param code
	 * @return    
	 */
	@Override
	public BarCode getLocationByCode(CodeMark code) {
		return cancellingStockMapper.getLocationByCode(code);
	}

	@Override
	public int caceltk(Map map) {
		// TODO Auto-generated method stub
		return cancellingStockMapper.caceltk(map);
	}

	@Override
	public int restortk(Map map) {
		// TODO Auto-generated method stub
		return cancellingStockMapper.restortk(map);
	}

	@Override
	public String queryCode(String code) {
		// TODO Auto-generated method stub
		return cancellingStockMapper.queryCode(code);
	}

	/**
	 * 物料的库存查询
	 * @param number 物料零件号
	 * @param warehouse_id 仓库ID
	 * @param search_type 查询类型（0：零件号查询，1：库位查询）
	 * @return
	 */
	@Override
	public Map<String, Object> appGetLocationByNumber(String number, String warehouse_id, String search_type) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<ZcMaterielInfoEntity> reList = new ArrayList<>();
		List<ZcMaterielInfoEntity> returnList = new ArrayList<>();;
		if("0".equals(search_type)){
			//按照零件号查询库存
			reList = cancellingStockMapper.appGetLocationInfoByMaterielNum(number, warehouse_id);
		}else{
			//按照库位查询库存
			reList = cancellingStockMapper.appGetLocationInfoByLocationNum(number, warehouse_id);
		}
		if(reList.size() > 0){
			//2、对库位进行去重
			/*Set<String> locationSet = new HashSet<>();
			for(ZcMaterielInfoEntity materielCode : reList){
				locationSet.add(materielCode.getLocation_code());
			}*/
			List<String> newList = new  ArrayList<String>(); 
	         for (ZcMaterielInfoEntity materielCode:reList) {
	            if(!newList.contains(materielCode.getLocation_code())){
	                newList.add(materielCode.getLocation_code());
	            }
	        }
			//3、统计每个库位下的条码和数量
			for(String location : newList){
				//3.1、创建对象存库位和该库位对应的条码的信息
				ZcMaterielInfoEntity temp = new ZcMaterielInfoEntity();
				List<CodeMark> codeList = new ArrayList<>();
				//3.2、把库位存入对象
				temp.setLocation_code(location);
				//3.3、找到库位下的条码，以及数量
				for(ZcMaterielInfoEntity materiel : reList){
					CodeMark cm = new CodeMark();
					if(location.equals(materiel.getLocation_code())){
						cm.setCode(materiel.getMaterielCode());
						cm.setNum(materiel.getmNum());
						cm.setPici(materiel.getmBatch());
						cm.setLinear_weight(materiel.getMaterielWeight());
						//3.3.1、统计该库位下条码数量的和计, 重量和计
						temp.setmNum(temp.getmNum() + materiel.getmNum());
						if(temp.getMaterielWeight() != null && materiel.getMaterielWeight() != null){
							temp.setMaterielWeight(StringUtil.calcFloatValue(temp.getMaterielWeight(), materiel.getMaterielWeight(), "add"));
						}
						//3.3.2、统计该库位下条码
						codeList.add(cm);
					}
					//释放资源
					cm = null;
					
					
				}
				//3.4、把对象存入结果的集合中
				temp.setCodeMark(codeList);
				returnList.add(temp);
				//释放资源
				codeList = null;
				temp = null;
			}
			map.put("status", "1");
			map.put("data", returnList);
		}else{
			map.put("status", "0");
			map.put("message", "无数据");
		}
		return map;
	}

}
